package com.briup.ptp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.ptp.mapper.EmployeeMapper;
import com.briup.ptp.entity.Employee;
import com.briup.ptp.service.EmployeeService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
* @author xuyang
* @description 针对表【employee】的数据库操作Service实现
* @createDate 2024-02-19 20:14:00
*/
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService{
    @Autowired
    EmployeeMapper mapper;

    //一、分页+条件查询员工信息
    @Override
    public PageInfo<Employee> page(String name, String position, String health, Integer pageNum, Integer pageSize) {
        List<Employee> list = mapper.page(name,position,health);
        PageInfo<Employee> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //二、新增+修改员工信息
    @Override
    public int saveOrUpdateEmployee(Employee employee) {
        //首先，使用Optional.ofNullable(employee)创建一个Optional<Employee>对象optionalEmployee，用于检查employee是否为null
        Optional<Employee> optionalEmployee = Optional.ofNullable(employee);
        if (optionalEmployee.isPresent()) {//Optional.isPresent()方法的作用是检查Optional对象(这里用id来判断的)是否包含一个非null的值,如果为空直接return0,不为null才进入if循环
            Employee existingEmployee = optionalEmployee.get();
            Integer id = existingEmployee.getId();

            //如果id是非空的或者是对应调试的id在数据库中匹配到的数量大于0的时候————则调试的id对应的员工存在，我们就调用更新操作的方法；否则，则调试的id对应的员工是不存在的，我们就调用新增操作的方法
            if (id != null && mapper.countEmployeeById(id) > 0) {
                // 员工已存在，更新员工信息
                return mapper.updateEmployee(id, existingEmployee.getName(), existingEmployee.getPosition(), existingEmployee.getGender(), existingEmployee.getAge(), existingEmployee.getDate(),existingEmployee.getHealth(),existingEmployee.getSalary());
            } else {
                // 员工不存在，插入新员工信息
                return mapper.insertEmployee(existingEmployee.getName(), existingEmployee.getPosition(), existingEmployee.getGender(), existingEmployee.getAge(), existingEmployee.getDate(),existingEmployee.getHealth(),existingEmployee.getSalary());
            }
        }
        //如果要调试的id数据等于null,两个方法都不调用，直接返回0
        return 0;
    }


    //三、根据员工id删除员工信息
    @Override
    public void deleteById(Integer id) {
        mapper.deleteById(id);
    }

    //四、批量删除员工信息
    //可以不用自己重新写抽象方法，直接可以使用继承的现成的ServiceImpl里的相关方法(removeByIds)
}




